<template>
  <div v-loading="loading">
    <div class="text-right mb-3" v-if="viewMode">
      <el-button @click="handlePrint">
        <i class="fa fa-fw fa-print"></i>
        打印
      </el-button>
      <el-button @click="handleExport" :loading="downloadLoading">
        <i class="fa fa-fw fa-download"></i>
        导出
      </el-button>
    </div>
    <div :id="printId">
      <table class="w-100">
        <tbody>
          <tr>
            <td colspan="11">
              <h3 class="text-center">{{ tableTitle }}</h3>
            </td>
          </tr>
          <tr>
            <td colspan="11" class="text-left">
              表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：G1表
            </td>
          </tr>
          <tr>
            <td colspan="11" class="text-left">制表机关：中国银行保险监督管理委员会</td>
          </tr>
          <tr>
            <td colspan="11" class="text-left">数据单位：万元</td>
          </tr>
          <tr class="bd-0">
            <td colspan="6" width="50%" class="text-left">
              填报单位：{{ tableInfo.service_name || orgName }}
            </td>
            <td colspan="5" class="text-left">{{ dateLabel }}</td>
          </tr>
        </tbody>
      </table>

      <table class="table table-bordered text-center table-vertical-middle table-sm mb-0">
        <colgroup>
          <col width="5%" />
          <col width="14%" />
          <col width="7%" />
          <col width="7%" />
          <col width="8%" />
          <col width="10%" />
          <col width="9%" />
          <col width="13%" />
          <col width="9%" />
          <col width="9%" />
          <col width="9%" />
        </colgroup>
        <tbody>
          <tr class="bd-1">
            <td rowspan="2">序号</td>
            <td>A</td>
            <td>B</td>
            <td>C</td>
            <td>D</td>
            <td>E</td>
            <td>F</td>
            <td>G</td>
            <td>H</td>
            <td>I</td>
            <td>J</td>
          </tr>
          <tr class="bd-1">
            <td>融资担保机构名称（全称）</td>
            <td>是否为国有控股融资担保机构</td>
            <td>是否为政府性融资担保机构</td>
            <td>融资担保业务经营许可证编号</td>
            <td>主体信用评级</td>
            <td>实收资本</td>
            <td>成立时间</td>
            <td>年末融资担保在保余额</td>
            <td>年末单户1000万元以下小微企业直接融资担保在保余额</td>
            <td>年末单户1000万元以下农户及新型农业经营主体直接融资担保在保余额</td>
          </tr>
          <tr class="bd-1">
            <td>合计</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td>-</td>
            <td></td>
            <td>-</td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
          <tr class="bd-1">
            <td>1</td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.service_name || orgName }}</span>
              <el-input
                v-else
                v-model="editData.service_name"
                placeholder="担保公司名称"
              ></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ enumIsOrNo[tableInfo.is_state_gua] || '' }}</span>
              <c-select
                v-else
                v-model="editData.is_state_gua"
                placeholder="请选择"
                :options="enumIsOrNo"
              ></c-select>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ enumIsOrNo[tableInfo.is_gov_gua] || '' }}</span>
              <c-select
                v-else
                v-model="editData.is_gov_gua"
                placeholder="请选择"
                :options="enumIsOrNo"
              ></c-select>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.bus_license }}</span>
              <el-input
                v-else
                v-model="editData.bus_license"
                placeholder="经营许可证编号"
              ></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.credit_lever }}</span>
              <el-input v-else v-model="editData.credit_lever" placeholder="评级"></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.paid_in_capital }}</span>
              <el-input
                v-else
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.paid_in_capital"
                placeholder="实收资本"
              ></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ dateFormat(tableInfo.establish_date, 'yyyy年MM月') }}</span>
              <el-date-picker
                v-else
                v-model="editData.establish_date"
                class="w-100"
                size="mini"
                placeholder="成立时间"
                type="month"
                value-format="yyyy-MM"
                :clearable="true"
              ></el-date-picker>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.end_year_left_funds }}</span>
              <el-input
                v-else
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.end_year_left_funds"
                placeholder="年末在保余额"
              ></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.end_year_sme_left_funds }}</span>
              <el-input
                v-else
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.end_year_sme_left_funds"
                placeholder="小微企业在保余额"
              ></el-input>
            </td>
            <td :class="tdClass">
              <span v-if="viewMode">{{ tableInfo.end_year_farmer_left_funds }}</span>
              <el-input
                v-else
                v-input-number="{ min: 0, fixed: 2 }"
                v-model="editData.end_year_farmer_left_funds"
                placeholder="新型农业在保余额"
              ></el-input>
            </td>
          </tr>
          <tr v-for="item in 6" class="bd-1" :key="item">
            <td>{{ item + 1 }}</td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
          </tr>
        </tbody>
      </table>

      <table class="w-100">
        <tbody>
          <tr>
            <td class="text-left" colspan="3" width="20%">统计负责人：</td>
            <td colspan="3" width="50%">
              填表人及联系方式：{{ tableInfo.submit_person_name || user.realName }}
              {{ tableInfo.phone_number || user.phoneNumber }}
            </td>
            <td colspan="5" width="30%">报出日期：{{ createDate }}</td>
          </tr>
          <tr>
            <td colspan="11" class="text-left" rowspan="9">
              <div class="mt-3">
                <pre class="report-desc">{{ reportDesc }}</pre>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="mb-5 text-center" v-if="!viewMode">
      <el-button :loading="saveLoading" class="btn-long" type="primary" @click="save">
        保存
      </el-button>

      <el-button class="mr-2 btn-long" :loading="saveLoading" @click="beforeClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumIsOrNo } from '@/credit/views/city/reportCity/manage/year/minxix'
import { dateFormat, excelTableExport, domHasClass, printWithIframe } from '@vimi/utils-tool'
export default {
  components: {},
  props: {
    queryYear: {
      type: Number,
      required: true,
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      dateFormat,
      enumIsOrNo,
      reportDesc: `填报说明：
1.本表由各省、自治区、直辖市融资担保公司监督管理部门填报。
2.本表统计范围为在本省（区、市）持有融资担保业务经营许可证的融资担保法人机构，不含融资担保机构的分支机构。
3.外币数据须按报告期末最后一天国家外汇管理局公布的基准汇价折合为人民币数据进行汇总。
4.成立时间准确到月，填写类型为：20XX年XX月。
5.填列的金额按四舍五入保留整数；报表中划横线部分不需填列。
6.小微企业、农户及新型农业经营主体交叉的，可以重复统计。
7.本报表为年报，报送时间为年后1月底前。
`,
      downloadLoading: false,
      tableName: 'report_year',
      tableTitle: 'XX省（区、市）融资担保公司名录',
      params: {
        'year_type.eq': 1,
      },
      tableInfo: {},
      editData: {},
      order: {},
      loading: false,
      saveLoading: false,
    }
  },
  computed: {
    ...mapGetters(['org', 'user', 'clientId']),
    orgName() {
      return this.org.orgName
    },
    dateLabel() {
      return `${this.queryYear}年`
    },
    createDate() {
      return dateFormat(this.tableInfo.update_time || new Date(), 'yyyy年MM月dd日')
    },
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    printId() {
      return `g1-${this.queryYear}`
    },
  },
  watch: {
    queryYear: {
      handler: function () {
        this.params['service_id.eq'] = this.clientId
        this.params['year_number.eq'] = this.queryYear
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          const data = res?.data?.[0] ?? { service_name: this.orgName }
          this.tableInfo = data
          this.editData = data
        })
        .finally(() => {
          this.loading = false
        })
    },
    save() {
      const data = {
        year_type: 1,
        report_no: 'G1表',
        establish_date: this.editData.establish_date,
        report_name: this.tableTitle,
        res_person: this.user.realName,
        phone_number: this.user.phoneNumber,
        year_number: this.queryYear,
        service_id: this.clientId,
        submit_person_name: this.user.realName,
        service_name: this.orgName,
        bus_license: this.editData.bus_license,
        credit_lever: this.editData.credit_lever,
        end_year_farmer_left_funds: this.editData.end_year_farmer_left_funds,
        end_year_left_funds: this.editData.end_year_left_funds,
        end_year_sme_left_funds: this.editData.end_year_sme_left_funds,
        is_gov_gua: this.editData.is_gov_gua,
        is_state_gua: this.editData.is_state_gua,
        paid_in_capital: this.editData.paid_in_capital,
      }
      this.saveLoading = true
      if (!this.editData.report_year_id) {
        this.$api
          .addData(this.$serviceName, this.tableName, data)
          .then(() => {
            this.$message.success('添加成功！')
            this.beforeClose()
            this.$emit('success', true)
          })
          .catch(err => {
            const errStr = typeof err.data === 'string' ? err.data : '添加失败，请重试！'
            return this.$message.error(`${errStr}`)
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .updateData(this.$serviceName, this.tableName, this.editData.report_year_id, data)
          .then(() => {
            this.$message.success('修改成功！')
            this.beforeClose()
            this.$emit('success', true)
          })
          .catch(err => {
            const errStr = typeof err.data === 'string' ? err.data : '修改失败，请重试！'
            return this.$message.error(`${errStr}`)
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    beforeClose() {
      this.editData = { ...this.tableInfo }
      this.$emit('close', false)
    },
    handlePrint() {
      printWithIframe(document.getElementById(this.printId))
    },
    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const borderAllNone = {
        left: { style: 'none' },
        top: { style: 'none' },
        right: { style: 'none' },
        bottom: { style: 'none' },
      }

      this.downloadLoading = true
      excelTableExport(this.printId, this.tableTitle, {
        styles: {
          border: borderAllNone,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 24,
              name: '方正小标宋简体',
            },
          },
          A34: {
            alignment: {
              vertical: 'top',
              wrapText: true,
            },
          },
          A7: {
            border: borderAllThin,
          },
        },
        rows: {
          0: { hpx: 48 },
          33: { hpx: 180 },
        },
        cellHandler({ value, tr, td }) {
          const style = {}

          if (domHasClass(tr, 'bd-1')) {
            style.border = borderAllThin
          } else if (domHasClass(tr, 'bd-0')) {
            style.border = borderAllNone
          }

          if (domHasClass(td, 'text-right')) {
            style.alignment = { horizontal: 'bottom' }
          } else if (domHasClass(td, 'text-left')) {
            style.alignment = { horizontal: 'top' }
          }

          const { className = '' } = td
          const indent = /text-indent-(\d+)/.exec(className)
          if (indent) {
            value = `${' '.repeat(+(indent[1] || 0) * 8)}${value}`
          }

          return { value, style }
        },
      }).finally(() => {
        this.downloadLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
$indents: 1, 2, 3;
@each $i in $indents {
  .text-indent-#{$i} {
    text-indent: $i * 2rem;
  }
}

.report-desc {
  font-size: 1rem;
  white-space: pre-wrap;
  font-family: 'Microsoft Yahei', '\5FAE\8F6F\96C5\9ED1', Helvetica, Arial, sans-serif;
}

.input-td {
  background: #ffffee;
}
</style>
